<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="js/fun.js" type="text/javascript"></script>
        <script src="js/config.js" type="text/javascript"></script>
        <script src="js/device.js" type="text/javascript"></script>
        <script src="js/logic_connect.js" type="text/javascript"></script>
        <script src="data/logicconnect.js" type="text/javascript"></script>
    </head>
    <style type="text/css">
        body{background: #517470}
        canvas{background: #517470}
    </style>
    <script type="text/javascript">
        var canvas = null;//保存画布.
        var unit_id = 40;//要画出的设备号
        var dataStep1 = logicConnectData;//逻辑回路json数据
        var chart = null;//绘图对象
        function pageLoad(){
            var can = $$('canvas');
            canvas = can.getContext('2d');
            can.width = window.innerWidth - 60;
            can.height = window.innerHeight - 60;
            //传入canvas对象，与事件坐标参数
            var windowToCanvas = function(canvas, x, y){
                var bbox;
                bbox = canvas.getBoundingClientRect();
                return {
                    x: (x - bbox.left) * (canvas.width / bbox.width),
                    y: (y - bbox.top) * (canvas.height / bbox.height)
                };
            };
            $$('canvas').onclick = function(){
                var point = windowToCanvas(this, event.clientX, event.clientY);
                var port = chart.getPortByPoint(point.x, point.y);
                if(port != null){
                    var msg ="";  
                    for(var name in port){
                        if(name == 'data'){
                            var dataMsg = "";
                            for(var k in port[name]){
                                dataMsg += k+":"+port[name][k]+',';
                            }
                            msg += name+": {"+ dataMsg+"}\n "; 
                        }else{
                            msg += name+": "+ port[name]+"\n "; 
                        } 
                    } 
                    alert(msg);
                    console.log(port);
                }
            };
            //接续数据，画图
            chart = LogicConnectChart.parseFrom(unit_id,  dataStep1);
            if(can.width < chart.getTotalWidth()){
                can.width = chart.getTotalWidth() + 100;
            }
            if(can.height < chart.getTotalHeight()){
                can.height = chart.getTotalHeight() + 100;
            }
            chart.x = (can.width - chart.getTotalWidth()) / 2;
            chart.y = (can.height - chart.getTotalHeight()) / 2;
            chart.draw(canvas);
        }
        function $$(id){
            return document.getElementById(id);
        }
    </script>
    <body onload="pageLoad();">
        <canvas id="canvas" width="400px" height="300px">4</canvas>
    </body>
</html>